package io.renren.modules.app.controller;

import io.renren.common.exception.RRException;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.Assert;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.service.UserService;
import io.renren.modules.sys.entity.CodeEntity;
import io.renren.modules.sys.entity.UserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.Date;

/**
 * 短信
 * @author wangyi
 * @mail 794651397@qq.com
 * @createdate 2018/3/22 10:16
 **/
@Api(description = "短信")
@RestController
@RequestMapping("/app")
public class ApiSMSController {
    @Value("${accesskey}")
    private String accesskey;//accesskey
    @Value("${accessSecret}")
    private String accessSecret;//accessSecret
    @Value("${sign}")
    private String sign;//签名
    @Value("${templateId}")
    private String templateId;//模板

    @Autowired
    private UserService userService;
    @Autowired
    private HttpServletRequest request;

    private String code=getRandNum(1,999999);

    /**
     * 注册 获取验证码
     * @author wangyi
     * @createdate 2018/3/22 10:18
     **/
    @ApiOperation("注册 获取验证码")
     @PostMapping("getSMSCodeRegister")
     public R getSMSCodeRegister(String mobile){
         Assert.isBlank(mobile, "手机号不能为空");
         UserEntity userEntity=userService.queryByMobile(mobile);
         if(userEntity!=null){
             throw new RRException("此手机号已注册账号,请直接登陆");
         }
         int result=changeCode(mobile);
         if(result>0){
             sendsms(mobile,code,"5分钟");
             return R.ok("短信发送成功,请注意查收");
         }else{
             throw new RRException("请重新发送验证码");
         }
     }

    /**
     * 忘记密码 获取验证码
     * @author wangyi
     * @createdate 2018/3/22 10:18
     **/
    @ApiOperation("忘记密码 获取验证码")
    @PostMapping("getSMSCodeForget")
    public R getSMSCodeForget(String mobile){
        Assert.isBlank(mobile, "手机号不能为空");
        UserEntity userEntity=userService.queryByMobile(mobile);
        if(userEntity==null){
            throw new RRException("此手机号还未注册账号,请先注册");
        }
        int result=changeCode(mobile);
        if(result>0){
            sendsms(mobile,code,"5分钟");
            return R.ok("短信发送成功,请注意查收");
        }else{
            throw new RRException("请重新发送验证码");
        }
    }

    /**
     * 修改密码 获取验证码
     * @author wangyi
     * @createdate 2018/3/22 10:18
     **/
    @ApiOperation("修改密码 获取验证码*{需要登陆的token}*")
    @Login
    @PostMapping("getSMSCodePassword")
    public R getSMSCodePassword(){
        Long userId=(Long)request.getAttribute("userId");
        UserEntity userEntity=userService.queryObject(userId);
        String mobile=userEntity.getMobile();
        int result=changeCode(mobile);
        if(result>0){
            sendsms(mobile,code,"5分钟");
            return R.ok("短信发送成功,请注意查收");
        }else{
            throw new RRException("请重新发送验证码");
        }
    }

    public int changeCode(String mobile){
        CodeEntity codeEntity=userService.queryCodeByMobile(mobile);
        Date expireDate = new Date(new Date().getTime() + 5 * 60 * 1000);
        int result=0;
        if(codeEntity!=null){
            codeEntity.setCode(code);
            codeEntity.setExpire(DateUtils.getTime(expireDate));
            result=userService.updateCode(codeEntity);
        }else{
            codeEntity=new CodeEntity();
            codeEntity.setMobile(mobile);
            codeEntity.setCode(code);
            codeEntity.setExpire(DateUtils.getTime(expireDate));
            result=userService.addCode(codeEntity);
        }
        return result;
    }


    //普通短信
    private void sendsms(String mobile,String code,String times) {
        try {
            HttpClient httpClient = new HttpClient();
            PostMethod postMethod = new PostMethod("http://api.1cloudsp.com/api/v2/single_send");
            postMethod.getParams().setContentCharset("UTF-8");
            postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

            NameValuePair[] data = {
                    new NameValuePair("accesskey", accesskey),
                    new NameValuePair("secret", accessSecret),
                    new NameValuePair("sign", sign),
                    new NameValuePair("templateId", templateId),
                    new NameValuePair("mobile", mobile),
                    new NameValuePair("content", URLEncoder.encode(code + "##" + times, "utf-8"))//（示例模板：{1}您好，您的订单于{2}已通过{3}发货，运单号{4}）
            };
            postMethod.setRequestBody(data);

            int statusCode = httpClient.executeMethod(postMethod);
            if (statusCode != 200) {
                throw new RRException("短信服务器错误");
            }
            String body = postMethod.getResponseBodyAsString();
            JSONObject JSON = JSONObject.fromObject(body);
            System.out.println("JSON = " + JSON);
            if (!JSON.get("code").equals("0")) {
                throw new RRException("短信服务器错误");
            }
        }catch (Exception e){
            throw new RRException("短信服务器错误");
        }
    }

    private String getRandNum(int min, int max) {
        int randNum = min + (int)(Math.random() * ((max - min) + 1));
        return String.valueOf(randNum);
    }

}
